﻿using UnityEngine;
using static EColor;

[RequireComponent(typeof(CTilemap))]
//玩家碰撞后可获得能量的平台
public class Platform_Energy : Platform_Collide
{
    protected Color color_active;               //激活时的颜色
    protected Color color_inactive;
    [SerializeField]
    protected float t_change = 1f;              //发光或变暗过程的最大时间
    protected Color presentColor;               //当前光效的颜色
    [SerializeField]
    protected float _Counter;                   //记录上次active改变后已经历的时间，用于确定光效的颜色
    protected virtual float Counter
    {
        get => _Counter;
        set
        {
            if (value > t_change)
                return;
            _Counter = value;
            if (Active)
                presentColor = Color.Lerp(color_inactive, color_active, _Counter / t_change);
            else
                presentColor = Color.Lerp(color_active, color_inactive, _Counter / t_change);
            canvas.SetColor(presentColor);
        }
    }

    protected override void OnStart()
    {
        switch(targetColor)
        {
            case Blue:
                color_active = Color.blue;
                break;
            case Green:
                color_active = Color.green;
                break;
            default:
                color_active = Color.white;
                break;
        }
        color_inactive = color_active.ResetAlpha(0f);
        canvas.DrawLight(tilePositions, tiles);
        OnPlayerDie();
    }

    protected override void OnEnable()
    {
        base.OnEnable();
        eventSystem.PlayerDie += OnPlayerDie;
        eventSystem.TouchGround += OnTouchGround;
    }
    protected override void OnDisable()
    {
        base.OnDisable();
        eventSystem.PlayerDie -= OnPlayerDie;
        eventSystem.TouchGround -= OnTouchGround;
    }

    private void FixedUpdate()
    {
        Counter += Time.fixedDeltaTime;
    }

    protected override void OnActivate(bool active)
    {
        Counter = 0;
    }

    protected virtual void OnTouchGround()
    {
        Active = true;
    }

    protected virtual void OnPlayerDie()
    {
        Active = true;
        Counter = t_change;
    }

    protected override void OnPlayerCollide(Vector2 normalLine, GameObject platform,Character player) 
    {
        if (gameObject == platform && Active)
        {
            Active = false;
        }
        else if(gameObject != platform && !Active)
        {
            Active = true;
        }
    }
}
